import { createApp } from 'vue';
import App from './App.vue';

// 引入封装的路由
import Router from './routers/index';

// 引入VantUI
import Vant from 'vant';
// 引入所有组件基础样式
import 'vant/lib/index.css';

// 引入封装的请求
import Http from '@/services/request';

// 引入工具函数
import Utils from '@/utils/utils';

// 引入状态管理
import { createPinia } from 'pinia';
// 引入状态管理持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

// 引入cookie
import vue3Cookies from 'vue3-cookies';

const app = createApp(App)
.use(Router)
.use(Vant)
.use(Http)
.use(createPinia().use(piniaPluginPersistedstate))
.use(Utils)
.use(vue3Cookies)
.mount('#app');

// 全局前置路由守卫
Router.beforeEach(async (to,from) =>
{
    const isLogin = to?.meta?.isLogin === true ? true : false;

    if(isLogin === true)
    {
        // 获取用户登录信息
        const business = app.$business;

        if(!business.value || Object.getOwnPropertyNames(business.value).length === 0)
        {
            app.$fail('请先登录');

            return {path:'/business/login'}
        }

        const id = business.value.id ?? 0;
        const mobile = business.value.mobile ?? '';

        const params = {
            id,
            mobile
        }

        const result = await app.$http.post('/business/check',params);

        if(result.code === 1)
        {
            app.$business.value = result.data;

            // 放行
            return true;
        }else{
            app.$business.value = {};

            app.$fail(result.msg);

            return {path:'/business/login'}
        }
    }
});